import json

from flask import Blueprint, render_template, request, current_app
import requests
from applications.common import curd
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import Role

admin_call_equip = Blueprint('adminCallequip', __name__, url_prefix='/admin/call_equip')


# 获取体征设备管理页面
@admin_call_equip.get('/')
def main():
    return render_template('admin/call_equip/main.html')


# 体征设备分页查询
@admin_call_equip.get('/data')
def data():
    page = request.args['page']
    page_size = request.args['limit']
    content = ''
    try:
        content = request.args['content']
    except:
        print('暂无设备名称')
    response = requests.post(url=current_app.config['EMERGENCY_URL'] + '/alarmdevs',
                             headers={
                                 'Content-type': 'application/json'
                             },
                             data=json.dumps({
                                 "page": int(page) - 1,
                                 "page_size": page_size,
                                 "total_count": True,
                                 "search": content
                             }))
    data = json.loads(response.text)
    data['code'] = 0
    data['count'] = response.headers['Total-Count']
    data['limit'] = page_size
    return data


# 情景增加
@admin_call_equip.get('/add')
def add():
    roles = Role.query.all()
    return render_template('admin/call_equip/add.html', roles=roles)


@admin_call_equip.post('/save')
def save():

    req_json = request.json
    print(req_json)
    a = req_json.get("roleIds")
    code = xss_escape(req_json.get('code'))
    sn = xss_escape(req_json.get('sn'))
    name = xss_escape(req_json.get('name'))
    x = xss_escape(req_json.get('x'))
    y = xss_escape(req_json.get('y'))
    z = xss_escape(req_json.get('z'))
    rx = xss_escape(req_json.get('rx'))
    ry = xss_escape(req_json.get('ry'))
    rz = xss_escape(req_json.get('rz'))
    map_id = xss_escape(req_json.get('map_id'))
    dept_parent_name = xss_escape(req_json.get('dept_parent_name'))
    dept_name = xss_escape(req_json.get('dept_name'))
    dept_id = xss_escape(req_json.get('deptId'))
    camera_id = xss_escape(req_json.get('camera_id'))
    camera_name = xss_escape(req_json.get('camera_name'))
    if not code or not sn or not dept_id:
        return fail_api(msg="设备编号、sn码、部门编号不得为空")
    response = add_api(code, sn, name, x, y, z, rx, ry, rz, map_id, dept_id, camera_id)
    if response['code']==200:
        return success_api(msg="增加成功")
    else :
        return fail_api(msg=response['message'])


def add_api(code,sn,name,x,y,z,rx,ry,rz,map_id,dept_id,camera_id):
    body = {
        "code": code,
        "sn": sn,
        "name": name,
        "x": float(x),
        "y": float(y),
        "z": float(z),
        "rx": float(rx),
        "ry": float(ry),
        "rz": float(rz),
        "map_id": int(map_id),
        "dept_id": int(dept_id),
        "camera_id": int(camera_id),
    }
    print(body)
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/alarmdevs/create', json=body).json()
    return req

# 删除情景
@admin_call_equip.delete('/remove/<int:id>')
@authorize("admin:call_equip:remove", log=True)
def delete(id):
    body = {
        "ids": [id]
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/alarmdevs/delete', json=body).json()
    if req['code']==200:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg=req['message'])


#  编辑情景
@admin_call_equip.get('/edit')
@authorize("admin:call_equip:edit", log=True)
def edit():
    print("Hello world")
    call_equip=request.args.to_dict()
    roles = Role.query.all()
    checked_roles = []
    for r in roles:
        checked_roles.append(r.id)

    return render_template('admin/call_equip/edit.html', call_equip=call_equip, roles=roles, checked_roles=checked_roles)


#  编辑情景
@admin_call_equip.put('/update')
def update():
    req_json = request.json
    x = xss_escape(req_json.get('x'))
    y = xss_escape(req_json.get('y'))
    z = xss_escape(req_json.get('z'))
    rx = xss_escape(req_json.get('rx'))
    ry = xss_escape(req_json.get('ry'))
    rz = xss_escape(req_json.get('rz'))
    map_id = xss_escape(req_json.get('map_id'))
    dept_id = xss_escape(req_json.get('deptId'))
    camera_id = xss_escape(req_json.get('camera_id'))
    req_json['x'] = float(x)
    req_json['y'] = float(y)
    req_json['z'] = float(z)
    req_json['rx'] = float(rx)
    req_json['ry'] = float(ry)
    req_json['rz'] = float(rz)
    req_json['map_id'] = int(map_id)
    req_json['dept_id'] = int(dept_id)
    req_json['camera_id'] = int(camera_id)
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/alarmdevs/update', json=req_json).json()
    if req['code'] == 200:
        return success_api(msg="更新成功")
    else:
        return fail_api(msg=req['message'])


# 批量删除
@admin_call_equip.delete('/batchRemove')
@authorize("admin:call_equip:remove", log=True)
def batch_remove():
    ids = list(map(int, request.form.getlist('ids[]')))
    body = {
        "ids": ids
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/alarmdevs/delete', json=body).json()
    print(req)
    if req['code']==200:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg=req['message'])